package top.huntwolf.admin.service;

import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.huntwolf.admin.dao.RouteDao;
import top.huntwolf.admin.pojo.Banner;
import top.huntwolf.admin.pojo.cmsUser.Permission;
import top.huntwolf.admin.pojo.cmsUser.Route;

import java.util.*;
import java.util.stream.Collectors;

@Service
@Transactional
public class RouteService {
    @Autowired
    private RouteDao routeDao;

    @Autowired
    private CMSUserService cmsUserService;

    public List<Route> searchAllRoute(){

        List<Route> childrenRoutes = routeDao.selectAll();

        return getRoutes(childrenRoutes);

    }


    public List<Route> getRoutes(List<Route> childrenRoutes) {
        List<Route> parentRoutes = new ArrayList<>();
        while (childrenRoutes.size()>0&&childrenRoutes.get(0)!=null){
            Route children = childrenRoutes.get(0);
            Route parentRoute = routeDao.selectById(children.getParentId());
            List<Route> MyChildren = childrenRoutes.stream().filter(route -> route.getParentId().equals(parentRoute.getId())).collect(Collectors.toList());
            childrenRoutes = childrenRoutes.stream().filter(route -> !route.getParentId().equals(parentRoute.getId())).collect(Collectors.toList());
            parentRoute.setChildren(MyChildren);
            parentRoutes.add(parentRoute);
        }
        return parentRoutes;
    }

    public void deleteRoute(Integer id){
        routeDao.delete(id);
    }
    public void insertRoute(Route route){
        routeDao.insert(route);
    }
    public void updateRoute(Route route){
        routeDao.update(route);
    }

    public List<Route> searchRouteTable(){

        List<Permission> permissions = cmsUserService.findPermission();
        return getChildrenRoutes(permissions);
    }

    public Route searchRoute(Integer id){
        return routeDao.selectById(id);
    }

    public List<Route> searchRouteByRoleId(Integer roleId){
        List<Permission> permissions = cmsUserService.searchPermissionByRoleId(roleId);
        return getChildrenRoutes(permissions);
    }

    public List<Route> getChildrenRoutes(List<Permission> permissions) {
        Set<Integer> routeIdSet = new HashSet<>();
        List<Route> childrenRoutes = new ArrayList<>();
        for (Permission permission : permissions){
            if(routeIdSet.add(permission.getRouteId())){
                childrenRoutes.add(routeDao.selectById(permission.getRouteId()));
            }
        }
        return getRoutes(childrenRoutes);
    }


}
